<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>创建空间</title>
    <base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style type="text/tailwindcss">
        @layer utilities {
            .form-input {
                @apply w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200;
            }
            .form-label {
                @apply block text-sm font-medium text-gray-700 mb-1;
            }
            .form-group {
                @apply mb-4;
            }
            .error-message {
                @apply text-red-500 text-sm mt-1;
            }
            .radio-group {
                @apply flex items-center space-x-4;
            }
            .radio-option {
                @apply flex items-center;
            }
            .radio-input {
                @apply w-4 h-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded;
            }
            .radio-label {
                @apply ml-2 text-sm font-medium text-gray-700;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航 -->
<header class="bg-white shadow-sm sticky top-0 z-10">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-2">
            <i class="fa fa-cloud text-blue-600 text-xl"></i>
            <h1 class="text-lg font-semibold text-gray-800">云存储空间管理</h1>
        </div>
        <nav>
            <ul class="flex space-x-6">
                <li><a href="OssServlet?method=list" class="text-gray-600 hover:text-blue-600 transition">存储空间列表</a></li>
                <li><a href="#" class="text-gray-600 hover:text-blue-600 transition">使用统计</a></li>
                <li><a href="#" class="text-gray-600 hover:text-blue-600 transition">帮助文档</a></li>
            </ul>
        </nav>
    </div>
</header>

<!-- 主要内容 -->
<main class="flex-1 container mx-auto px-4 py-8">
    <div class="max-w-2xl mx-auto bg-white rounded-xl shadow-md overflow-hidden border border-gray-200">
        <div class="bg-blue-600 text-white p-4">
            <h2 class="text-xl font-bold flex items-center">
                <i class="fa fa-pencil-square-o mr-2"></i>编辑存储空间
            </h2>
        </div>

        <div class="p-6">
            <form id="ossForm" method="post" enctype="multipart/form-data">
                <input type="hidden" name="id" value="${requestScope.book.id}">
                <input type="hidden" name="pageNo" value="${param.pageNo}">
                <input type="hidden" name="method" value="saveOrUpdate">

                <div class="form-group">
                    <label for="bucketName" class="form-label">存储空间名称</label>
                    <div class="relative">
                        <input id="bucketName" value="${requestScope.book.name}" name="bucketName" type="text" class="form-input" maxlength="63">
                        <div id="bucketNameLength" class="absolute right-3 top-2 text-xs text-gray-400">
                            <span id="currentLength">0</span>/63
                        </div>
                    </div>
                    <div id="bucketNameError" class="error-message"></div>
                </div>

                <div class="form-group">
                    <label class="form-label">存储类型</label>
                    <div class="radio-group">
                        <label class="radio-option">
                            <input type="radio" name="type" value="标准存储" ${requestScope.book.type == '标准存储'? 'checked' : ''} class="radio-input">
                            <span class="radio-label">标准存储</span>
                        </label>
                        <label class="radio-option">
                            <input type="radio" name="type" value="低频访问存储" ${requestScope.book.type == '低频访问存储'? 'checked' : ''} class="radio-input">
                            <span class="radio-label">低频访问存储</span>
                        </label>
                        <label class="radio-option">
                            <input type="radio" name="type" value="归档存储" ${requestScope.book.type == '归档存储'? 'checked' : ''} class="radio-input">
                            <span class="radio-label">归档存储</span>
                        </label>
                    </div>
                    <div id="typeError" class="error-message"></div>
                </div>

                <div class="form-group">
                    <label class="form-label">访问权限</label>
                    <div class="radio-group">
                        <label class="radio-option">
                            <input type="radio" name="permission" value="私有(Pr)" ${requestScope.book.permission == '私有(Pr)'? 'checked' : ''} class="radio-input">
                            <span class="radio-label">私有(Pr)</span>
                        </label>
                        <label class="radio-option">
                            <input type="radio" name="permission" value="公共读(R)" ${requestScope.book.permission == '公共读(R)'? 'checked' : ''} class="radio-input">
                            <span class="radio-label">公共读(R)</span>
                        </label>
                        <label class="radio-option">
                            <input type="radio" name="permission" value="公共读写(RW)" ${requestScope.book.permission == '公共读写(RW)'? 'checked' : ''} class="radio-input">
                            <span class="radio-label">公共读写(RW)</span>
                        </label>
                    </div>
                    <div id="permissionError" class="error-message"></div>
                </div>

                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="history.back()" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition duration-200 flex items-center">
                        <i class="fa fa-arrow-left mr-1"></i> 返回
                    </button>
                    <button type="submit" id="submitBtn" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg shadow-md transition-all duration-200 flex items-center gap-2 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                        <i class="fa fa-check-circle"></i> 保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</main>

<footer class="bg-gray-800 text-white py-4">
    <div class="container mx-auto px-4 text-center">
        <p>© 2025 云存储空间管理系统 |吴沁林 版权所有</p>
    </div>
</footer>

<script src="static/script/jquery-1.7.2.js"></script>
<script>

    $(document).ready(function() {
        $("#ossForm").on("submit", function(e) {
            e.preventDefault();
            validateAndSubmit();
        });

        // 实时验证存储空间名称
        $("input[name='bucketName']").on("blur", function() {
            validateBucketName($(this).val());
        });

        // 验证并提交表单
        function validateAndSubmit() {
            var bucketName = $("input[name='bucketName']").val();
            var type = $("input[name='type']:checked").val() || '';
            var permission = $("input[name='permission']:checked").val() || '';

            // 重置所有错误信息
            $(".error-message").text("");

            var isValid = true;

            // 验证存储空间名称
            if (!validateBucketName(bucketName)) {
                isValid = false;
            }

            // 验证存储类型
            if (!type) {
                $("#typeError").text("请选择存储类型");
                isValid = false;
            }

            // 验证访问权限
            if (!permission) {
                $("#permissionError").text("请选择访问权限");
                isValid = false;
            }

            if (!isValid) {
                return false;
            }

            // 使用AJAX提交表单
            var formData = new FormData(document.getElementById("ossForm"));

            $.ajax({
                url: "OssServlet?method=saveOrUpdate",
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $("#submitBtn").prop("disabled", true).html('<i class="fa fa-spinner fa-spin"></i> 提交中...');
                },
                success: function(response) {
                    if (response.success) {
                        // 显示成功通知
                        showNotification("操作成功", "success");
                        setTimeout(() => {
                            window.location.href = "${pageContext.request.contextPath}/index.jsp";
                        }, 3500);
                    } else {
                        showNotification(response.message || "操作失败", "error");
                        $("#submitBtn").prop("disabled", false).html('<i class="fa fa-check-circle"></i> 提交');
                    }
                },
                error: function() {
                    showNotification("网络错误，请重试", "error");
                    $("#submitBtn").prop("disabled", false).html('<i class="fa fa-check-circle"></i> 提交');
                }
            });
        }

        // 验证存储空间名称
        function validateBucketName(name) {
            var isValid = true;
            if (!name.trim()) {
                $("#bucketNameError").text("存储空间名称不能为空");
                isValid = false;
            }else {
                // 检查名称是否重复（异步验证）
                checkNameExists(name, function(exists) {
                    if (exists) {
                        $("#bucketNameError").text("存储空间名称已存在");
                    }
                });
            }

            return isValid;
        }

        // 检查名称是否存在
        function checkNameExists(name, callback) {
            var id = $("input[name='id']").val();

            $.ajax({
                url: "OssServlet?method=checkNameExists",
                type: "GET",
                data: {
                    name: name,
                    id: id
                },
                dataType: 'json', // 强制指定JSON格式
                success: function(response) {
                    callback(response.exists);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    callback(false);
                }
            });
        }

        // 显示通知
        function showNotification(message, type) {
            console.log(message)
            var notification = $("<div>")
                .addClass("fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full")
                .addClass(type === "success" ? "bg-green-500 text-white" : "bg-red-500 text-white");

            // 创建图标元素
            var icon = $("<i>")
                .addClass(`fa ${type == "success" ? "fa-check-circle" : "fa-exclamation-circle"} mr-2`);

            // 将图标和消息文本添加到通知中
            notification.append(icon).append(document.createTextNode(message));
            $("body").append(notification);

            // 通知
            setTimeout(() => {
                notification.removeClass("translate-x-full");
            }, 10);
            //通知关闭
            setTimeout(() => {
                notification.addClass("translate-x-full");
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 3000);
        }

        // 初始化字节计数
        updateLengthCounter();

        $("input[name='bucketName']").on("input", function() {
            updateLengthCounter();
            validateBucketName($(this).val());
        });

        // 更新字节计数
        function updateLengthCounter() {
            var input = $("input[name='bucketName']");
            var value = input.val();
            var length = getBytesLength(value);

            // 更新字节计数显示
            $("#currentLength").text(length);

            // 如果超过63字节，则不允许在输入
            if (length > 63) {
                var maxChars = 0;
                var byteCount = 0;

                while (byteCount <= 63 && maxChars < value.length) {
                    var code = value.charCodeAt(maxChars);
                    byteCount += code > 255 ? 2 : 1;
                    if (byteCount <= 63) maxChars++;
                }
                // 截断字符串
                input.val(value.substring(0, maxChars));
                updateLengthCounter(); // 重新更新计数
            }
        }
    });
</script>
</body>
</html>